﻿using System;
using System.IO;
using System.Net;
using System.Text;

namespace COC.Webs
{
    class GetHttpData
    {
        private string _RetString = "";
        private readonly char[] _Cbuffer = new char[256];
        private int _ByteRead = 0;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postDataStr"></param>
        /// <returns></returns>
        public string HttpGet(string url, string postDataStr)
        {
            HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url + (postDataStr == "" ? "" : "?") + postDataStr);
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";

            HttpWebResponse response = (HttpWebResponse) request.GetResponse();
            Stream stream = response.GetResponseStream();
            if (stream != null)
            {
                StreamReader reader = new StreamReader(stream, Encoding.GetEncoding("utf-8"));
                //说明：原来整个页面获取完成后才解析，速度太慢，因此此处改为找到一个结束标记“Discussions about”就终止读取，直接解析数据
                _ByteRead = reader.Read(_Cbuffer, 0, 256);
                while (_ByteRead != 0)
                {
                    string strResp = new string(_Cbuffer, 0, _ByteRead);
                    _RetString = _RetString + strResp;
                    if (_RetString.IndexOf("Discussions about", StringComparison.CurrentCultureIgnoreCase) > -1)
                    {
                        break;
                    }
                    _ByteRead = reader.Read(_Cbuffer, 0, 256);
                }
                reader.Close();
                stream.Close();
            }
            return _RetString;
        }
    }
}
